package com.cartoonrabbit.controller;

import com.cartoonrabbit.pojo.User;
import com.cartoonrabbit.service.AuthService;
import com.cartoonrabbit.service.IUserService;
import com.cartoonrabbit.vo.AuthPhoneNumberParam;
import com.cartoonrabbit.vo.LoginParam;
import com.cartoonrabbit.vo.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.security.Principal;

@RestController
@RequestMapping("/wx/auth")
@Api(tags = "微信认证接口")
public class WxAuthController {

    @Autowired
    private IUserService userService;

    @Autowired
    private AuthService authService;


    @ApiOperation(value = "一键登录功能")
    @PostMapping("/login")
    public RespBean login(@RequestBody LoginParam loginParam) {
        String tokenKey = authService.login(loginParam);
        return RespBean.success("SUCCESS",tokenKey);
    }

    @ApiOperation(value = "获取用户手机号")
    @PostMapping("/getPhoneNumber")
    public RespBean getPhoneNumber(@RequestBody AuthPhoneNumberParam phoneNumberParam) {
        Object phoneObject= authService.doGetPhoneNumber(phoneNumberParam);
        return RespBean.success("SUCCESS",phoneObject);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/userInfo")
    public RespBean getUserInfo(Principal principal){
        if (principal==null){
            return new RespBean(401,"未登录",null);
        }
        User user = authService.getUserInfoByOpenId(principal.getName());
        return RespBean.success("SUCCESS",user);
    }

    @ApiOperation("用户修改用昵称")
    @PreAuthorize("@ss.permitAll()")
    @PostMapping(value = "/updateUsername")
    public RespBean updateUsername(String nickname,Principal principal){
        if (principal==null){
            return new RespBean(401,"未登录",null);
        }
        if (ObjectUtils.isEmpty(nickname)||nickname.trim().length()==0){
            return RespBean.fail("用户名不能为空");
        }
        return userService.updateUsername(nickname,principal.getName());
    }

    @ApiOperation("用户修改头像")
    @PreAuthorize("@ss.permitAll()")
    @PostMapping(value = "/updateAvatar",produces = {"application/json;charset=UTF-8"})
    public RespBean updateAvatar(@RequestParam("avatar")MultipartFile avatarFile,Principal principal){
        if (principal==null){
            return new RespBean(401,"未登录",null);
        }
        if (ObjectUtils.isEmpty(avatarFile)){
            return RespBean.fail("上传图片不能为空");
        }
        // 判断格式是否是图片
        if (!avatarFile.getContentType().contains("image")){
            return RespBean.fail("上传的文件非图片格式");
        }
        return userService.updateAvatar(avatarFile,principal.getName());
    }
}
